import hashlib
import hmac
import time
import requests
import uuid
import urllib
import sys
import json

from coin2.api_client.common import (SyncQueryer)
from coin.exchange.base.kr_rest.auth_base import AuthKey


class BitstampAuth(requests.auth.AuthBase):
  def __init__(self, key):
    self._key = AuthKey.from_file(key)

  def __call__(self, req: requests.PreparedRequest):
    parsed_result = urllib.parse.urlparse(req.url)
    api_host = parsed_result.netloc
    path = parsed_result.path
    if req.body is None:
      req.body = "offset=1"

    timestamp = str(int(round(time.time() * 1000)))
    nonce = str(uuid.uuid4())
    content_type = 'application/x-www-form-urlencoded'
    message = 'BITSTAMP ' + self._key.access_key + \
        'POST' + \
        api_host + \
        path + \
        '' + \
        content_type + \
        nonce + \
        timestamp + \
        'v2' + \
        req.body

    message = message.encode(encoding='utf-8')
    signature = hmac.new(self._key.secret_key_bytes,
                         msg=message, digestmod=hashlib.sha256).hexdigest()
    req.headers.update({'X-Auth': 'BITSTAMP ' + self._key.access_key,
                        'X-Auth-Signature': signature,
                        'X-Auth-Nonce': nonce,
                        'X-Auth-Timestamp': timestamp,
                        'X-Auth-Version': 'v2',
                        'Content-Type': content_type
                        })

    return req


class BitstampPrivateClient():
  def __init__(self, key, mea, ip=None):
    self._key = key
    if mea == "Spot.Bitstamp.v2":
      self._url = 'https://www.bitstamp.net'
    self._auth = BitstampAuth(key)
    self._query = SyncQueryer(api_host=self._url, auth=self._auth, ip=ip)

  def get_open_order(self, timeout=None):
    method = "POST"
    path = "/api/v2/open_orders/all/"
    response = self._query.query(
        method=method, path=path, params=None, timeout=timeout)
    return response


if __name__ == "__main__":
  key_path = sys.argv[1]
  config = dict()
  config["key_path"] = key_path
  config["mea"] = "Spot.Bitstamp.v2"
  bit =  BitstampPrivateClient(key_path, "Spot.Bitstamp.v2", None)
  resp = bit.get_open_order()
  print(json.dumps(resp, indent=2))
